<?php
/**
 * Permission Service
 * User: zng
 * Date: 2019/11/4
 * Time: 14:34
 */
namespace app\admin\service\curriculum;

use app\admin\model\curriculum\Curriculum as CurriculumModels;

Class Curriculum {

    /**
     * 首页列表
     * @param array $get 筛选条件
     * @return \think\Paginator
     */
    public function indexPaginate( array $get=[] )
    {
        $map = [];
        if ( get($get, 'name') ) {
            $map[] = ['name', 'LIKE', $get['name'].'%'];
        }
        $config = config('field.curriculum');
        if ( in_array(get($get, 'type'), $config['type']) ) {
            $map[] = ['type', '=', $get['type']];
        }
        if ( get($get, 'cycle') ) {
            $map[] = ['start_cycle', '<=', $get['cycle']];
            $map[] = ['end_cycle', '>=', $get['cycle']];
        }
        $pageSize = get($get,'pageSize')>0?$get['pageSize']:20;
        return CurriculumModels::where($map)
            ->order('id', 'desc')
            ->paginate($pageSize);
    }

    /**
     * 新增主课程信息
     * @param array $data 数据包
     * @return boolean|integer
     */
    public function create(array $data)
    {
        $curriculum = CurriculumModels::create($data, ['name','cover','start_cycle','end_cycle','type','origin_price','price','detail','category']);
        return $curriculum->isEmpty()?false:$curriculum->id;
    }

    /**
     * 关联新增
     * @param int $cid
     * @param array $tid
     * @return mixed
     */
    public function relatedCreate(int $cid, array $tid)
    {
        return CurriculumModels::get($cid)->teacher()->saveAll($tid);
    }

    /**
     * 关联删除
     * @param int $cid
     * @param array $tid
     * @return mixed
     */
    public function relatedDelete(int $cid)
    {
        return CurriculumModels::get($cid)->teacher()->detach();
    }

    /**
     * 批量删除
     * @param mixed $data
     * @return boolean
     */
    public function destory( $data )
    {
        return CurriculumModels::destroy(function($query)use($data){
            $where = ['id', '=', $data];
            if ( is_array($data) ) {
                $where = ['id', 'in', $data];
            }
            $query->where([
                $where
            ]);
        });
    }

    /**
     * 主课程管理编辑
     * @param CurriculumModels $model
     * @param array $data
     */
    public function save(CurriculumModels $model, array $data)
    {
        $model->name = $data['name'];
        $model->cover = $data['cover'];
        $model->start_cycle = $data['start_cycle'];
        $model->end_cycle = $data['end_cycle'];
        $model->type = $data['type'];
        $model->origin_price = $data['origin_price'];
        $model->price = $data['price'];
        $model->detail = $data['detail'];
        $model->category = $data['category'];
        return $model->save();
    }

    /**
     * 获取主课程集合
     *
     * @return array
     */
    public function getList()
    {
        return CurriculumModels::field('id,name')->select()->toArray();
    }

}